import Divider from 'antd/es/divider';
import { AppStore, EViewType } from '../../../../store';
import { useMemo, useState } from 'react';
import TextArea from 'antd/es/input/TextArea';
import { ButtonProps } from 'antd/es/button/button'
import { IBomFittingData, IBomFittingRenderProperty, IBomPlankGrooveEditable, IBomPlankHoleEditable } from '@manycore/custom-ksg-viewer-sdk';
import message from 'antd/es/message/index'
import { flattenModels } from '../../../../util';
import AutoComplete from 'antd/es/auto-complete';
import Input from 'antd/es/input';

export function BOMFittingViewerDemo(props: {
    createButton: (infos: Array<{
        /** buttonName */
        name: string,
        onClick: () => void;
        buttonProps?: ButtonProps;
    }>) => JSX.Element[]
}) {
    const { createButton } = props;
    const { appState: { app, jsonData, viewInfo } } = AppStore.useContainer();
    const [fittings, setFittings] = useState<string>();
    const [inputModelId, setInputModelId] = useState<string>();
    const [orderId, setOrderId] = useState<string>();

    const models = useMemo(() => {
        return flattenModels(jsonData?.paramModel || []);
    }, [jsonData]);

    const CApis = [
        {
            name: '一键写入模型关联的全部孔槽',
            disabled: true,
            onClick: async () => {
                try {
                    if (!orderId) {
                        message.error('请先输入产品所在的订单id！');
                        return;
                    }
                    if (viewInfo?.type !== EViewType.Design) {
                        message.error('暂时只支持设计方案模型关联的孔槽数据');
                        return;
                    }
                    const { result: planks } = await Manycore.Integration.Bom.findPlankListAsync({ productIds: Array.isArray(viewInfo.info.modelId) ? viewInfo.info.modelId : [viewInfo.info.modelId], orderIds: [orderId] });


                    /**
                     * 自定义孔槽渲染的规则
                     * 板件下的孔则展示紫色
                     * 五金下的孔则展示蓝色
                     * @param fitting 
                     * @returns 
                     */
                    function getFittingWithRenderProperty<T extends IBomPlankHoleEditable | IBomPlankGrooveEditable>(fitting: T): T & Partial<IBomFittingRenderProperty> {
                        if (fitting.type === "PLANK") {
                            return {
                                ...fitting,
                                renderProperty: {
                                    color: "#BA68C8",
                                    opacity: 0.9
                                }
                            }

                        } else if (fitting.type === "FITTING") {
                            return {
                                ...fitting,
                                renderProperty: {
                                    color: "#2CCCE4",
                                    opacity: 0.9
                                }
                            }
                        }

                        // 默认绿色 不透明
                        return fitting;
                    }

                    planks.forEach(plank => {
                        const newFittingData = {
                            ...plank,
                            holes: plank.holes.map(h => getFittingWithRenderProperty(h as unknown as IBomPlankHoleEditable)),
                            grooves: plank.grooves.map(g => getFittingWithRenderProperty(g as unknown as IBomPlankGrooveEditable))
                        };
                        app!.bomFittingViewerService.addFittings(newFittingData);
                    })
                }
                catch (err) {
                    message.error('孔槽数据为空或者数据格式不正确');
                }
            }
        },
        {
            name: '新增BOM孔槽',
            onClick: () => {
                try {
                    app!.bomFittingViewerService.addFittings(JSON.parse(fittings!) as IBomFittingData)
                }
                catch (err) {
                    console.error(err);
                    message.error('孔槽数据为空或者数据格式不正确');
                }
            }
        }, {
            name: '清除孔槽',
            onClick: () => {
                if (!inputModelId) {
                    message.error('请先输入或者择需要清除的孔槽关联的模型id');
                    return;
                }
                app!.bomFittingViewerService.removeFittings({
                    modelId: inputModelId
                })

            }
        }, {
            name: '清空全部孔槽',
            onClick: () => app!.bomFittingViewerService.clearFittings()
        }
    ]



    return <>
        <Divider> BOM孔槽</Divider>
        <Input placeholder='请输入订单id' value={orderId} onChange={(e) => setOrderId(e.target.value)}></Input>
        {createButton([CApis[0]])}
        <TextArea placeholder='请输入BOM孔槽数据' value={fittings} onChange={(e) => setFittings(e.target.value)}></TextArea>
        {createButton([CApis[1]])}
        <AutoComplete value={inputModelId} onChange={(data) => setInputModelId(data)} style={{ width: '100%' }} placeholder='输入或者选择待清除孔槽的模型id' options={models.map(m => ({ value: m.id }))} />
        {createButton([CApis[2]])}
        {createButton([CApis[3]])}
    </>
}